import { ref, computed, onMounted, onUnmounted } from 'vue'
import { taskNotificationService } from '../../shared/services/task-notification-service'
import { webSocketService } from '../../shared/services/websocket-service'
import type { TaskNotification } from '../../../types/task-notification'
import { TaskNotificationStatus, TaskNotificationType, isUnread } from '../../../types/task-notification'

export function useTaskNotificationManager() {
  // 通知列表
  const notifications = ref<TaskNotification[]>([])
  const unreadCount = ref(0)
  const loading = ref(false)
  const error = ref<string | null>(null)
  
  // 分页参数
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

  // 计算属性
  const hasUnreadNotifications = computed(() => unreadCount.value > 0)
  const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

  // 获取未读通知数量
  const fetchUnreadCount = async () => {
    try {
      unreadCount.value = await taskNotificationService.getUnreadCount()
    } catch (err) {
      console.error('获取未读通知数量失败:', err)
      error.value = '获取未读通知数量失败'
    }
  }

  // 获取通知列表
  const fetchNotifications = async (page = 1, reset = false) => {
    if (loading.value) return
    
    loading.value = true
    error.value = null
    
    try {
      const result = await taskNotificationService.getNotifications(page, pageSize.value)
      
      if (reset || page === 1) {
        notifications.value = result.list
      } else {
        notifications.value = [...notifications.value, ...result.list]
      }
      
      total.value = result.total
      currentPage.value = page
    } catch (err) {
      console.error('获取通知列表失败:', err)
      error.value = '获取通知列表失败'
    } finally {
      loading.value = false
    }
  }

  // 加载更多通知
  const loadMore = () => {
    if (currentPage.value < totalPages.value && !loading.value) {
      fetchNotifications(currentPage.value + 1)
    }
  }

  // 标记通知为已读
  const markAsRead = async (id: number) => {
    try {
      await taskNotificationService.markAsRead(id)
      
      // 更新本地状态
      const notification = notifications.value.find(n => n.id === id)
      if (notification && isUnread(notification)) {
        notification.isRead = true
        if (notification.type === TaskNotificationType.NOTIFICATION) {
          notification.status = TaskNotificationStatus.READ
        }
        unreadCount.value = Math.max(0, unreadCount.value - 1)
      }
    } catch (err) {
      console.error('标记通知为已读失败:', err)
      error.value = '标记通知为已读失败'
      throw err
    }
  }

  // 标记所有通知为已读
  const markAllAsRead = async () => {
    try {
      await taskNotificationService.markAllAsRead()
      
      // 更新本地状态
      notifications.value.forEach(notification => {
        notification.isRead = true
        if (notification.type === TaskNotificationType.NOTIFICATION) {
          notification.status = TaskNotificationStatus.READ
        }
      })
      unreadCount.value = 0
    } catch (err) {
      console.error('标记所有通知为已读失败:', err)
      error.value = '标记所有通知为已读失败'
      throw err
    }
  }

  // 删除通知
  const deleteNotifications = async (ids: number[]) => {
    try {
      await taskNotificationService.deleteNotifications(ids)
      
      // 更新本地状态
      const deletedNotifications = notifications.value.filter(n => ids.includes(n.id))
      const deletedUnreadCount = deletedNotifications.filter(n => isUnread(n)).length
      
      notifications.value = notifications.value.filter(n => !ids.includes(n.id))
      unreadCount.value = Math.max(0, unreadCount.value - deletedUnreadCount)
      total.value = Math.max(0, total.value - ids.length)
    } catch (err) {
      console.error('删除通知失败:', err)
      error.value = '删除通知失败'
      throw err
    }
  }

  // 删除已读通知
  const deleteReadNotifications = async () => {
    try {
      await taskNotificationService.deleteReadNotifications()
      
      // 更新本地状态
      const readNotifications = notifications.value.filter(n => !isUnread(n))
      const readCount = readNotifications.length
      
      notifications.value = notifications.value.filter(n => isUnread(n))
      total.value = Math.max(0, total.value - readCount)
    } catch (err) {
      console.error('删除已读通知失败:', err)
      error.value = '删除已读通知失败'
      throw err
    }
  }

  // 刷新通知列表
  const refresh = async () => {
    await Promise.all([
      fetchUnreadCount(),
      fetchNotifications(1, true)
    ])
  }

  // 存储WebSocket取消订阅的函数
  let unsubscribeNotifications: (() => void) | null = null

  // 监听WebSocket通知
  onMounted(async () => {
    // 订阅WebSocket通知
    if (webSocketService.isConnected()) {
      unsubscribeNotifications = webSocketService.subscribeToNotifications((message: any) => {
        // 处理普通通知
        if (message.type === 'notification') {
          // 将新通知添加到列表开头
          const notification: TaskNotification = {
            id: Date.now(), // 临时ID，实际应该从后端获取
            userId: 0, // 应该从用户状态获取
            taskId: message.taskId,
            taskType: message.taskType,
            type: TaskNotificationType.NOTIFICATION,
            status: TaskNotificationStatus.UNREAD,
            title: message.title || '通知',
            content: message.content,
            isRead: false,
            createTime: new Date().toISOString()
          };
          
          notifications.value.unshift(notification);
          unreadCount.value++;
        }
        // 处理任务完成通知
        else if (message.type === 'task_completion') {
          // 创建一个符合TaskNotification接口的通知对象
          const notification: TaskNotification = {
            id: Date.now(), // 临时ID，实际应该从后端获取
            userId: 0, // 应该从用户状态获取
            taskId: message.taskId,
            taskType: message.taskId?.split('_')[0] || 'unknown',
            type: TaskNotificationType.TASK,
            status: message.status === 'success' ? TaskNotificationStatus.COMPLETED : TaskNotificationStatus.FAILED,
            title: '任务完成',
            content: message.message,
            result: JSON.stringify({
              status: message.status,
              timestamp: message.timestamp
            }),
            isRead: false,
            createTime: new Date().toISOString()
          };
          
          // 将新通知添加到列表开头
          notifications.value.unshift(notification);
          unreadCount.value++;
          
          console.log('收到任务完成通知:', notification);
        }
        // 处理任务进度更新
        else if (message.type === 'task_progress') {
          // 查找是否已有该任务的通知
          const existingIndex = notifications.value.findIndex(n => 
            n.taskId === message.taskId && n.type === TaskNotificationType.TASK
          );
          
          if (existingIndex >= 0) {
            // 更新现有通知
            notifications.value[existingIndex].status = TaskNotificationStatus.RUNNING;
            notifications.value[existingIndex].content = message.message;
            notifications.value[existingIndex].progress = message.progress;
          } else {
            // 创建新的进度通知
            const notification: TaskNotification = {
              id: Date.now(), // 临时ID，实际应该从后端获取
              userId: 0, // 应该从用户状态获取
              taskId: message.taskId,
              taskType: message.taskId?.split('_')[0] || 'unknown',
              type: TaskNotificationType.TASK,
              status: TaskNotificationStatus.RUNNING,
              title: '任务进行中',
              content: message.message,
              progress: message.progress,
              isRead: false,
              createTime: new Date().toISOString()
            };
            
            notifications.value.unshift(notification);
            unreadCount.value++;
          }
        }
      })
    }
    
    // 初始加载通知数据
    await refresh()
  })

  // 组件卸载时取消订阅
  onUnmounted(() => {
    if (unsubscribeNotifications) {
      unsubscribeNotifications()
      unsubscribeNotifications = null
    }
  })

  return {
    // 状态
    notifications,
    unreadCount,
    loading,
    error,
    currentPage,
    pageSize,
    total,
    
    // 计算属性
    hasUnreadNotifications,
    totalPages,
    
    // 方法
    fetchUnreadCount,
    fetchNotifications,
    loadMore,
    markAsRead,
    markAllAsRead,
    deleteNotifications,
    deleteReadNotifications,
    refresh
  }
}